﻿using Castle.Core.Logging;
using com.ytocargo.Application.BackgroundJobs;
using com.ytocargo.Application.FlightInfos;
using System;
using Yto.Common.Dependency;
using Yto.Common.Extensions;
using Yto.Unitwork;

namespace com.ytocargo.Application.FlightInfo4Monitors
{
    public class SendFlightInfo4MWorker : BackgroundJob<SendFlightInfo4MArgs>, ITransient
    {
        private ILogger _logger;
        private ICtnManager _ctnManager;
        private readonly IFlightInfo4MonitorServices _flightInfo4MonitorServices;
        private readonly IBackgroundJobManager _jobManager;
        private IUnitManager _unitManager;

        public SendFlightInfo4MWorker(ICtnManager ctnManager,
            IFlightInfo4MonitorServices flightInfo4MonitorServices,
            IBackgroundJobManager jobManager,
            IUnitManager unitManager)
        {
            _ctnManager = ctnManager;
            _logger = ctnManager.IsRegisted<ILoggerFactory>() ?
                ctnManager.Resolver<ILoggerFactory>().Create(typeof(SendFlightInfo4MWorker))
                : NullLogger.Instance;
            _flightInfo4MonitorServices = flightInfo4MonitorServices;
            _jobManager = jobManager;
            _unitManager = unitManager;
        }

        public override void Execute(SendFlightInfo4MArgs Args)
        {
            var filter = new FlightInfoFilter();
            filter.FlightDate = Convert.ToDateTime(DateTime.Now.AddDays(1).ToShortDateString());
            using (var uw = _unitManager.Begin())
            {
                var list = _flightInfo4MonitorServices.GetListByMap(filter);
                MqHelper.SendMq("AirLines_FlightDynamic", "CAST.HYT.FlightDynamic", list.ToJsonString(), _logger);
                list.ForEach(x =>
                {
                    _flightInfo4MonitorServices.UpdateOrInsert(x);
                });
                uw.Complete();
            }
        }
    }
}
